#include<bits/stdc++.h>
#define ONLINE_JUDGE
#define ll long long
#define ull unsigned long long
using namespace std;

const ll N = 1e6 + 10, INF = 0x3f3f3f3f;

ll gcd(ll a, ll b) { return b != 0 ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }

ll mip(ll a)
{
    for (ll i = 2;i * i <= a;i++)
        if (a % i == 0) return i;
    return a;
}

void solve()
{
    ll a, b; cin >> a >> b;
    if (a == b) { cout << 0 << '\n'; return; }
    if (b % a == 0) { cout << b << '\n'; return; }
    ll g = gcd(a, b), p = mip(a), q = mip(b);
    if (g != 1) { cout << a + b << '\n';return; }
    cout << min({ lcm(a,b),lcm(a,2) + lcm(2,b),lcm(a,p) + lcm(p,b),lcm(a,q) + lcm(q,b) , lcm(a,p) + lcm(p,2) + lcm(2,b),lcm(a,2) + lcm(2,q) + lcm(q,b) , lcm(a,p) + lcm(p,q) + lcm(q,b),lcm(a,p) + lcm(p,2) + lcm(2,q) + lcm(q,b) }) << '\n';
}

signed main()
{
    // ios::sync_with_stdio(0);
    // cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    ll T = 1;
    cin >> T;
    for (ll i = 1;i <= T;i++) {
        solve();
    }
}